var utils = {};

//格式化字符串
utils.formatStr = function(){
    var args = Array.prototype.slice.call(arguments,1);
    var count=0;
    //通过正则替换%s
    return arguments[0].replace(/%s/g,function(s,i){
        return args[count++];
    });
}

//返回操作
utils.back = function(toActivityName){
    if(!back()){
        swipe(0, device.height/2, device.width/2, device.height/2, 1000);
    }
    if(toActivityName){
        waitForActivity(toActivityName);
    }else{
        sleep(2000);
    }
}

utils.click = function(ele,rect){
    var bound = ele.bounds();

    var intersec = utils.intersection(bound,rect);

    if(intersec == null){
        console.log("click无有效区域。。。");
        return false;
    }
    var pressResult= false;
    var pointX,pointY;
    while(!pressResult){
        pointX = parseInt((intersec.left + (intersec.right - intersec.left)/4));
        pointY = parseInt((intersec.top + intersec.bottom)/2);
        pressResult = press(pointX,pointY,150);
        toastLog(utils.formatStr("点击坐标(%s,%s)",pointX,pointY));
        if(!pressResult){
            toastLog(utils.formatStr("点击坐标(%s,%s) 失效",pointX,pointY));
        }
        sleep(1000);
    }
    return true;
}

//求两个区域交集
utils.intersection = function(rect1,rect2){
    if(!rect2){
        return rect1;
    }
    var top = Math.max(rect1.top,rect2.top);
    var left = Math.max(rect1.left,rect2.left);
    var bottom = Math.min(rect1.bottom,rect2.bottom);
    var right = Math.min(rect1.right,rect2.right);

    if(top < bottom && left < right){
        return {top:top,left:left,bottom:bottom,right:right};
    }else{
        return null;
    }

}

//判断当前脚本是否正在执行 不允许重复执行
utils.isRunning = function(){
    var engine = engines.myEngine();
    var state = engines.all().find(e=>{return e.getId() != engine.getId() && e.getSource().toString()==engine.getSource().toString()
        && e.cwd()==engine.cwd();}) != undefined;
    return state;
}

//放在脚本最上面 重复执行的脚本直接退出
utils.exitIfRepeat = function(){
    if(utils.isRunning()){
        toast("当前脚本正在执行，无需重复操作");
        exit();
    }
}

//请求脚本 并传递参数
utils.postJs= function(scriptUrl,config){
    var DownJs = dialogs.build({
        title: "正在请求脚本中……",
        progress: {
            max: -1
        },
        cancelable: false
    }).show();
    try{
        var res_script = http.get(scriptUrl, {
            headers: {
                'Accept-Language': 'en-us,en;q=0.5',
                'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
            }
        });
    
        if (res_script.statusCode == 200) {
            DownJs.dismiss();
            toastLog("脚本获取成功");
            var jsContent = res_script.body.string();
            var e = engines.execScript("", jsContent,{path:files.cwd()+"/js"});
    
            setTimeout(()=>{
                //向该脚本发送事件
                e.getEngine().emit("start", config);
                },2000);
        } else {
            DownJs.dismiss();
            dialogs.alert("脚本获取失败！这可能是您的网络原因造成的，建议您检查网络后再重新运行软件吧\nHTTP状态码:" + res_script.statusMessage);
        }
    }catch(e){
        DownJs.dismiss();
        dialogs.alert("脚本获取失败！");
    
    }
}

utils.createFile = function(url,path){
    try{
        var fileName = /[^/]+$/.exec(url)[0];
        var res_script = http.get(url, {
            headers: {
                'Accept-Language': 'en-us,en;q=0.5',
                'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
            }
        });
        if (res_script.statusCode == 200) {
            files.write((path || '') + fileName,  res_script.body.string());
            return path;
        }
    }catch(e){
        throw e;
    }
    return null;
    
}

module.exports = utils;